﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CCF20Model.ModelBase;
using WiseLink.RDS.Resource;

namespace CCF20Model
{
    public partial class SMSModel : ModelBase.ModelBaseClass
    {
        public static List<string> FaultedCustomerShortMessageList = new List<string> { "a", "b" };
        public static List<string> NonFaultedCustomerShortMessageList = new List<string> { "广告", "索赔", "开机" };
        public static Dictionary<string, int> GPRSTypeIDLookup = new Dictionary<string, int> 
        { 
            { "保养", 2 }, { "位置", 6 }, { "故障",1 }, {"月度报告",5 }, {"开机",7 }, {"索赔",8 }, { "广告",3 } 
        };
        private static CCF20Entities ccf20Ent;

        public SMSModel(CCF20Entities ccf20):base(ccf20)
        {
            ccf20Ent = ccf20;
        }

        static SMSModel()
        {
            ccf20Ent = new CCF20Entities();
        }

        public static void SendMaintenanceMsg()
        {
            ccf20Ent = new CCF20Entities();
            SMSTemplate smsTemplate = ccf20Ent.SMSTemplates.Where(s => s.SMSType.Contains("保养") && s.SMSTitle.Contains("保养短信模板")).FirstOrDefault();
            if (smsTemplate == null)
            {
                LoggerHelper.LogCCF20("无法发送保养短信,找不到保养短信模板");
                return;
            }
            foreach (Vehicle v in ccf20Ent.Vehicles)
            {
                int a = v.VehicleID;
                int b = v.VehicleMaintenanceHistories.Count(m => m.IsActive = true && m.IsSMSed == false);
            }

            var query = ccf20Ent.Vehicles.Where(v => v.VehicleMaintenanceHistories.Count(h => h.IsActive == true && h.IsSMSed == false) > 0);

            //we need to force an eager loading here as foreach doesn't work well with SaveChange().
            // You can't commit a trans while not finish the foreach (read).
            foreach (Vehicle vehicle in query.ToList())
            {
                string smsText = FormatSMS(smsTemplate.SMSText, vehicle);
                SendShortMessage(vehicle, smsTemplate, smsText, true);
            }
        }
        public static string SendShortMessage(Vehicle vehicle, string smsType,string smsTitle,bool IsSystem = false)
        {
            SMSTemplate smsTemplate = ccf20Ent.SMSTemplates.Where(s => s.SMSType.Contains(smsType) && s.SMSTitle.Contains(smsTitle)).FirstOrDefault();
            
            if (smsTemplate != null)
            {
                string smsText = FormatSMS(smsTemplate.SMSText,vehicle);
                return SendShortMessage(vehicle, smsTemplate, smsText,IsSystem);
            }
            else
            {
                LoggerHelper.LogCCF20(string.Format("找不到短信模板 {0}", smsType));
                return string.Format("找不到短信模板 {0}", smsType);
            }
        }
        
        public static string SendShortMessage(Vehicle vehicle, SMSTemplate smsTemplate, string smsText,bool IsSystem = false)
        {

            string strResult = string.Empty;

            if (!IsSystem && vehicle.FaultCount == 0 && vehicle.MaintenanceCount == 0 && vehicle.UrgentCount == 0)
            {
                //给车主发短信时，对于既没有故障、保养、撞车的车主，除了广告模板短信和索赔模板之外，其他是不允许发送成功的
                if (NonFaultedCustomerShortMessageList.AsQueryable<string>().Count(s => s.Contains(smsTemplate.SMSType)) == 0)
                {
                    strResult = string.Format("客户{0}没有故障、保养和撞车的，只可以发送广告和索赔", vehicle.Customer.Name);
                    LoggerHelper.LogCCF20(strResult);
                    return strResult;
                }

            }
             List<string> smsList = SplitSMSTextByLength(smsText);
             smsList.ForEach(msg =>
                 {
                     SMSHistory smsHistory = new SMSHistory();
                     smsHistory.VehicleID = vehicle.VehicleID;
                     smsHistory.IsActive = true;
                     smsHistory.QueueTime = DateTime.Now;
                     smsHistory.SMSTemplateID = smsTemplate.SMSTemplateID;
                     smsHistory.SMSText = msg;
                     smsHistory.CustomerName = vehicle.Customer.Name;
                     smsHistory.CustomerMobile = vehicle.Customer.FirstMobile;
                     smsHistory.Operator = IsSystem ? "系统" : CurrentUser;
                     ccf20Ent.SMSHistories.AddObject(smsHistory);
                     strResult = string.Format("给客户{0}的{1}-{2}短信进入发送队列,客户手机号{3}",
                                            smsHistory.CustomerName,
                                            smsTemplate.SMSType,
                                            smsTemplate.SMSTitle,
                                            smsHistory.CustomerMobile);
                     LoggerHelper.LogCCF20(strResult);
                 });
            ccf20Ent.SaveChanges();
            return strResult;

        }
        public static bool SendGPRSMessage(Vehicle vehicle, string smsType,string smsTitle)
        {
            SMSTemplate smsTemplate = GetSMSTemplate(smsType, smsTitle);
            if (smsTemplate != null)
            {
                string smsText = FormatSMS(smsTemplate.SMSText, vehicle);
                return SendGPRSMessage(vehicle.Devices.First().IDCSimNumber,smsText,smsType);
            }
            else
            {
                LoggerHelper.LogCCF20(string.Format("找不到短信模板 {0} 标题 {1}", smsType, smsTitle));
                return false;
            }

        }

        public static SMSTemplate GetSMSTemplate(string smsType, string smsTitle)
        {
            SMSTemplate smsTemplate = ccf20Ent.SMSTemplates.Where(s => s.SMSType.Contains(smsType) && s.SMSTitle.Contains(smsTitle)).FirstOrDefault();
            
            if (smsTemplate != null)
            {
                return smsTemplate;
            }
            else
            {
                LoggerHelper.LogCCF20(string.Format("找不到短信模板 {0} 标题 {1}", smsType,smsTitle));
                return null;
            }

        }
        public static bool SendGPRSMessage(string idc,string message,string smsType)
        {
            if (GPRSTypeIDLookup.ContainsKey(smsType))
            {
                string gprsMsg = "{\"Idc\":\"" + idc + "\",\"Msg\":\"" + message + "\",\"Type\":\"" + GPRSTypeIDLookup[smsType] + "\" }";

                ZICBase.ExectueMethod(ZICMethod.AddGPRSMessage, new object[]{
                                                            ZICMonitorModel.ZICLoginInfo.IDSName,
                                                            ZICMonitorModel.ZICLoginInfo.IDSPassword,
                                                            gprsMsg});

                LoggerHelper.LogCCF20(string.Format("[成功]给IDC={0}发送 {1} 导航屏消息:{2}",idc,smsType, gprsMsg));
                return true;
            }
            else
            {
                LoggerHelper.LogCCF20(string.Format("[失败]给IDC={0}发送 {1} 导航屏消息:不在GPRS消息允许类型里", idc, smsType));
                return false;
            }

        }
        public static CustomizeTypeCollection<SMSTemplate> GetSMSTemplate()
        {
            //CCF20Entities ccf20Ent = new CCF20Entities();
            var query = from m in ccf20Ent.SMSTemplates
                        where !m.SMSType.Equals("事故") && !m.SMSType.Equals("管理")
                        orderby m.SMSTitle descending
                        select m;
            return new CustomizeTypeCollection<SMSTemplate>(query, ccf20Ent);
        }

        public static string GetSMSContent(string smsType,string smsTitle,Vehicle vehicle,string customerName = null)
        {
            SMSTemplate smsTemplate = ccf20Ent.SMSTemplates.Where(s => s.SMSType.Contains(smsType) && s.SMSTitle.Contains(smsTitle)).FirstOrDefault();
            string smsText = string.Empty;
            if (smsTemplate != null)
            {
                smsText = FormatSMS(smsTemplate.SMSText,vehicle,customerName);
            }
            else
            {
                LoggerHelper.LogCCF20(string.Format("找不到短信模板 {0}-{1}", smsType,smsTitle));
                smsText = string.Empty;
            }
            return smsText;
        }
        public static void ScheduleUrgentSMS()
        {
            foreach (UrgentSMSQueue urgentQueue in ccf20Ent.UrgentSMSQueues.Where(u => u.IsActive == true))
            {
                if (DateTime.Compare(DateTime.Now, (DateTime)urgentQueue.SendTime) > 0)
                {
                    List<string> smsList = SplitSMSTextByLength(urgentQueue.Content);
                    smsList.ForEach(msg =>
                        {
                            urgentQueue.IsActive = false;
                            urgentQueue.CloseReason = "已发送";
                            SMSHistory smsHistory = new SMSHistory();
                            smsHistory.VehicleID = urgentQueue.VehicleID;
                            smsHistory.IsActive = true;
                            smsHistory.QueueTime = DateTime.Now;
                            smsHistory.SMSText = msg;
                            smsHistory.CustomerName = urgentQueue.ReceiverName;
                            smsHistory.CustomerMobile = urgentQueue.ReceiverMobile;
                            smsHistory.Operator = "系统提醒";
                            ccf20Ent.SMSHistories.AddObject(smsHistory);
                            LoggerHelper.LogZICDebug(string.Format("[撞车提醒] Receiver={0} Mobile={1} VehicleID={2}",
                                                                        smsHistory.CustomerName,
                                                                        smsHistory.CustomerMobile,
                                                                        smsHistory.VehicleID));
                        });
                }
            }
            ccf20Ent.SaveChanges();
        }

        public static void ScheduleManagerReportSMS()
        {
            SMSTemplate smsTemplate = GetSMSTemplate("管理", "管理信息汇报模板");

            if (smsTemplate != null)
            {
                foreach (ManagerReportReceiver mrr in ccf20Ent.ManagerReportReceivers)
                {

                    List<string> smsList = SplitSMSTextByLength(FormatSMS(smsTemplate.SMSText, mrr.Name));
                    smsList.ForEach(msg =>
                        {

                            SMSHistory smsHistory = new SMSHistory();
                            smsHistory.IsActive = true;
                            smsHistory.QueueTime = DateTime.Now;
                            smsHistory.SMSText = msg;
                            smsHistory.CustomerName = mrr.Name;
                            smsHistory.CustomerMobile = mrr.Mobile;
                            smsHistory.Operator = "系统提醒";
                            smsHistory.SMSTemplateID = smsTemplate.SMSTemplateID;
                            ccf20Ent.SMSHistories.AddObject(smsHistory);
                            LoggerHelper.LogZICDebug(string.Format("[管理信息汇报] Receiver={0} Mobile={1} VehicleID={2}",
                                                                        smsHistory.CustomerName,
                                                                        smsHistory.CustomerMobile,
                                                                        smsHistory.VehicleID));
                        });

                }
                ccf20Ent.SaveChanges();
            }
        }

        public static void MonthlyReportSMS()
        {
            
            foreach (Vehicle goodVehicle in ccf20Ent.Vehicles.Where(v => v.Devices.Count>0 &&
                                                                         v.Faults.Count(f=>f.IsActive == true) ==0 && 
                                                                         v.VehicleMaintenanceHistories.Count(m=>m.IsActive == true) ==0))
            {
                //CreateSMSHistoryByVehicle("月度报告", "月度车辆体检报告模板（完全良好)", goodVehicle);
                SendGPRSMessage( goodVehicle,"月度报告", "月度车辆体检报告模板（完全良好)");
            }
            foreach (Vehicle needMaintenanceVehicle in ccf20Ent.Vehicles.Where(v => v.Devices.Count > 0 && 
                                                                                    v.VehicleMaintenanceHistories.Count(m => m.IsActive == true) > 0 && 
                                                                                    !v.LastContactResult.Contains(WiseLink.RDS.Resource.WiseLinkRDSStatus.Contact_InShop)))
            {
                //CreateSMSHistoryByVehicle("月度报告", "月度车辆体检报告模板（需要保养或者维修)", needMaintenanceVehicle);
                SendGPRSMessage(needMaintenanceVehicle, "月度报告", "月度车辆体检报告模板（需要保养或者维修)");
            }
            foreach (Vehicle inRepairMaintenanceVehicle in ccf20Ent.Vehicles.Where(v => v.Devices.Count > 0 && v.LastContactResult.Contains(WiseLink.RDS.Resource.WiseLinkRDSStatus.Contact_InShop)))
            {
                //CreateSMSHistoryByVehicle("月度报告", "月度车辆体检报告模板（正在维修中)", inRepairMaintenanceVehicle);
                SendGPRSMessage( inRepairMaintenanceVehicle,"月度报告", "月度车辆体检报告模板（正在维修中)");
            }

            ccf20Ent.SaveChanges();
            
            
        }

        private static void CreateSMSHistoryByVehicle(string templateType, string templateTitle,Vehicle vehicle)
        {
            SMSTemplate smsTemplate = GetSMSTemplate(templateType, templateTitle);
            if (smsTemplate != null)
            {
                List<string> smsList = SplitSMSTextByLength(FormatSMS(smsTemplate.SMSText, vehicle));
                smsList.ForEach(msg =>
                    {

                        SMSHistory smsHistory = new SMSHistory();
                        smsHistory.IsActive = true;
                        smsHistory.QueueTime = DateTime.Now;
                        smsHistory.SMSText = msg;
                        smsHistory.CustomerName = vehicle.Customer.Name;
                        smsHistory.CustomerMobile = vehicle.Customer.FirstMobile;
                        smsHistory.SMSTemplateID = smsTemplate.SMSTemplateID;
                        smsHistory.Operator = "系统提醒";
                        smsHistory.VehicleID = vehicle.VehicleID;
                        ccf20Ent.SMSHistories.AddObject(smsHistory);
                        LoggerHelper.LogZICDebug(string.Format("[{0}][{1}] Receiver={2} Mobile={3} VehicleID={4}\\r\\n{5}",
                                                                    templateType,
                                                                    templateTitle,
                                                                    smsHistory.CustomerName,
                                                                    smsHistory.CustomerMobile,
                                                                    smsHistory.VehicleID,
                                                                    smsHistory.SMSText));
                    });


            }

        }

        private static List<string> SplitSMSTextByLength(string smsText)
        {
            List<string> smsList = new List<string>();
            
            // we nolonger has the limitation on 70.
            
            //while (smsText.Length > 70)
            //{
            //    smsList.Add(smsText.Substring(0, 70));
            //    smsText = smsText.Substring(70);
            //}
            smsList.Add(smsText);
            return smsList;

        }
        
    }

}
